import type { Character, Message } from '../database/schema.js';
import { AIProviderFactory } from './ai/provider-factory.js';
import type { AIMessage, CharacterData } from './ai/types.js';

export class AIService {
  // 获取AI提供商实例
  private static getProvider() {
    return AIProviderFactory.getConfiguredProvider();
  }

  // 生成角色人设
  static async generateCharacter(background: string): Promise<{
    name: string;
    personality: string[];
    speakingStyle: string;
    knowledgeBase: string;
    systemPrompt: string;
  }> {
    try {
      const provider = this.getProvider();
      const characterData = await provider.generateCharacter(background);

      // 生成系统提示词
      const systemPrompt = this.generateSystemPrompt(characterData);

      return {
        ...characterData,
        systemPrompt,
      };
    } catch (error) {
      console.error('生成角色失败:', error);
      throw error;
    }
  }

  // 角色对话
  static async chat(
    character: Character,
    messages: Message[],
    userMessage: string
  ): Promise<string> {
    try {
      const provider = this.getProvider();

      // 构建对话历史
      const aiMessages: AIMessage[] = [
        { role: 'system', content: character.systemPrompt },
      ];

      // 添加历史消息（最近10条）
      const recentMessages = messages.slice(-10);
      for (const msg of recentMessages) {
        aiMessages.push({
          role: msg.role as 'user' | 'assistant',
          content: msg.content,
        });
      }

      // 添加当前用户消息
      aiMessages.push({
        role: 'user',
        content: userMessage,
      });

      return await provider.chat(aiMessages);
    } catch (error) {
      console.error('AI对话失败:', error);
      throw error;
    }
  }

  // 生成系统提示词
  private static generateSystemPrompt(character: {
    name: string;
    personality: string[];
    speakingStyle: string;
    knowledgeBase: string;
  }): string {
    return `你是${character.name}，一个虚拟角色。

性格特点：
${character.personality.join('、')}

说话风格：
${character.speakingStyle}

知识领域：
${character.knowledgeBase}

请严格按照以上设定进行角色扮演，保持角色的一致性。用第一人称回应用户，不要透露你是AI助手的身份。回答要生动有趣，符合角色设定。`;
  }

  // 获取AI提供商状态
  static getProviderStatus() {
    return AIProviderFactory.getProviderStatus();
  }

  // 手动指定使用特定提供商
  static async generateCharacterWithProvider(
    background: string,
    providerName: string
  ) {
    try {
      const provider = AIProviderFactory.createProvider(providerName);
      if (!provider.isConfigured()) {
        throw new Error(`${provider.getName()} 未配置`);
      }

      const characterData = await provider.generateCharacter(background);
      const systemPrompt = this.generateSystemPrompt(characterData);

      return {
        ...characterData,
        systemPrompt,
      };
    } catch (error) {
      console.error(`使用 ${providerName} 生成角色失败:`, error);
      throw error;
    }
  }
}
